package com.rbw.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.rbw.model.UserBean;
import com.rbw.service.UserService;

public class UserInterceptor extends HandlerInterceptorAdapter {
	private Logger logger = Logger.getLogger(this.getClass());

	@Autowired
	private UserService userServiceImpl;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		String sessionId = request.getSession().getId();
		logger.info("sessionId:" + sessionId);
		UserBean user = userServiceImpl.existUser(sessionId);
		if (user != null) {
			request.setAttribute("uid", user.getUid());
			request.setAttribute("user", user);
		} else {
			logger.info("ContextPath:" + request.getContextPath());
			response.sendRedirect(request.getContextPath() + "/login");
			return false;
		}

		return super.preHandle(request, response, handler);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}
}